﻿using ERPWinFormWork.Test.Test.Dtos;
using ERPWinFormWork.Test.Test.Dtos.Write;
using ERPWinFormWork.Test.TestCode;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERPWinFormWork.Test
{
    public partial class AddProcurement_Pricing : Form
    {
        private ApiClient _apiClient;

        public AddProcurement_Pricing()
        {
            InitializeComponent();
            _apiClient = new ApiClient(TestAPI.TestApiBaseUrl);

            // 统一UI美化
            ApplyUiPolish();

            // 配置数据表格
            ConfigureDataGridView();

            // 绑定表格事件
            BindGridEvents();

            // 绑定全局税率变化事件
            BindGlobalTaxRateEvents();

            // 加载下拉框数据
            LoadSuppliersAsync();

            // 生成核价编号：年月日时分秒+3位随机数
            textpricingNode.Text = $"PJ{DateTime.Now:yyyyMMddHHmmss}{new Random().Next(100, 999)}";


        }

        /// <summary>
        /// 统一UI美化
        /// </summary>
        private void ApplyUiPolish()
        {
            try
            {
                // 全局字体与背景
                this.Font = new Font("微软雅黑", 10.5F, FontStyle.Regular, GraphicsUnit.Point, 134);
                this.BackColor = Color.FromArgb(248, 250, 252);

                // 核价编号控件美化 - 设置为只读样式
                if (textpricingNode != null)
                {
                    textpricingNode.ReadOnly = true;
                    textpricingNode.BackColor = Color.FromArgb(245, 245, 245); // 浅灰色背景
                    textpricingNode.SkinTxt.BackColor = Color.FromArgb(245, 245, 245);
                    textpricingNode.SkinTxt.ForeColor = Color.FromArgb(64, 64, 64); // 深灰色文字
                    textpricingNode.SkinTxt.Font = new Font("微软雅黑", 9F, FontStyle.Bold); // 加粗字体
                }

                // 表格美化
                if (dgvmater != null)
                {
                    dgvmater.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
                    dgvmater.EnableHeadersVisualStyles = false;
                    dgvmater.ColumnHeadersHeight = 40;
                    dgvmater.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
                    dgvmater.RowTemplate.Height = 28;
                    dgvmater.GridColor = Color.FromArgb(224, 224, 224);

                    dgvmater.ColumnHeadersDefaultCellStyle.BackColor = Color.FromArgb(41, 128, 185);
                    dgvmater.ColumnHeadersDefaultCellStyle.ForeColor = Color.White;
                    dgvmater.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                    dgvmater.ColumnHeadersDefaultCellStyle.Font = new Font("微软雅黑", 10F, FontStyle.Bold);

                    dgvmater.DefaultCellStyle.Font = new Font("微软雅黑", 9F);
                    dgvmater.DefaultCellStyle.SelectionBackColor = Color.FromArgb(59, 188, 240);
                    dgvmater.DefaultCellStyle.SelectionForeColor = Color.White;

                    // 双缓冲，减少滚动/刷新闪烁
                    var pi = typeof(DataGridView).GetProperty("DoubleBuffered", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
                    pi?.SetValue(dgvmater, true, null);
                }

                // 按钮大小微调
                if (btnStepwiseAdd != null) btnStepwiseAdd.Size = new Size(90, 40);
                if (skinButton1 != null) skinButton1.Size = new Size(90, 40);
            }
            catch { }
        }

        /// <summary>
        /// 配置数据表格
        /// </summary>
        private void ConfigureDataGridView()
        {
            if (dgvmater != null)
            {
                dgvmater.AllowUserToAddRows = false;
                dgvmater.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
                dgvmater.MultiSelect = false;
                dgvmater.AutoGenerateColumns = false;

                // 清空现有列
                dgvmater.Columns.Clear();

                // 添加列
                dgvmater.Columns.Add(new DataGridViewTextBoxColumn
                {
                    Name = "colMaterialNumber",
                    HeaderText = "物料编号",
                    DataPropertyName = "MaterialNumber",
                    Width = 120,
                    ReadOnly = true
                });

                dgvmater.Columns.Add(new DataGridViewTextBoxColumn
                {
                    Name = "colMaterialName",
                    HeaderText = "物料名称",
                    DataPropertyName = "MaterialName",
                    Width = 150,
                    ReadOnly = true
                });

                dgvmater.Columns.Add(new DataGridViewTextBoxColumn
                {
                    Name = "colSpecifications",
                    HeaderText = "规格型号",
                    DataPropertyName = "Specifications",
                    Width = 120,
                    ReadOnly = true
                });

                dgvmater.Columns.Add(new DataGridViewTextBoxColumn
                {
                    Name = "colUnitName",
                    HeaderText = "单位",
                    DataPropertyName = "UnitName",
                    Width = 80,
                    ReadOnly = true
                });

                dgvmater.Columns.Add(new DataGridViewTextBoxColumn
                {
                    Name = "colTaxRate",
                    HeaderText = "税率(%)",
                    DataPropertyName = "TaxRate",
                    Width = 80,
                    ReadOnly = false
                });

                dgvmater.Columns.Add(new DataGridViewTextBoxColumn
                {
                    Name = "colOriginalUntaxedPrice",
                    HeaderText = "原未税价格",
                    DataPropertyName = "OriginalUntaxedPrice",
                    Width = 100,
                    ReadOnly = true
                });

                dgvmater.Columns.Add(new DataGridViewTextBoxColumn
                {
                    Name = "colOriginalTaxedPrice",
                    HeaderText = "原含税价格",
                    DataPropertyName = "OriginalTaxedPrice",
                    Width = 100,
                    ReadOnly = true
                });

                dgvmater.Columns.Add(new DataGridViewTextBoxColumn
                {
                    Name = "colUntaxedPrice",
                    HeaderText = "新未税价格",
                    DataPropertyName = "UntaxedPrice",
                    Width = 100,
                    ReadOnly = false
                });

                dgvmater.Columns.Add(new DataGridViewTextBoxColumn
                {
                    Name = "colTaxedPrice",
                    HeaderText = "新含税价格",
                    DataPropertyName = "TaxedPrice",
                    Width = 100,
                    ReadOnly = false
                });

                // 添加删除列
                if (!dgvmater.Columns.Contains("colDelete"))
                {
                    var deleteCol = new DataGridViewButtonColumn
                    {
                        Name = "colDelete",
                        HeaderText = string.Empty,
                        Text = "删除",
                        UseColumnTextForButtonValue = true,
                        Width = 70
                    };
                    dgvmater.Columns.Add(deleteCol);
                }
            }
        }

        /// <summary>
        /// 绑定表格事件
        /// </summary>
        private void BindGridEvents()
        {
            if (dgvmater != null)
            {
                // 绑定单元格值更改事件，用于计算价格
                dgvmater.CellValueChanged += Dgvmater_CellValueChanged;

                // 绑定单元格点击事件，用于删除操作
                dgvmater.CellContentClick += Dgvmater_CellContentClick;

                // 绑定数据绑定完成事件
                dgvmater.DataBindingComplete += Dgvmater_DataBindingComplete;
            }
        }

        /// <summary>
        /// 绑定全局税率变化事件
        /// </summary>
        private void BindGlobalTaxRateEvents()
        {
            if (texttax_Rate != null)
            {
                texttax_Rate.TextChanged += (s, e) =>
                {
                    UpdateAllMaterialTaxRates();
                };
            }
        }

        /// <summary>
        /// 更新所有物料的税率并重新计算价格
        /// </summary>
        private void UpdateAllMaterialTaxRates()
        {
            if (dgvmater == null || dgvmater.Rows.Count == 0) return;

            // 获取全局税率
            int globalTaxRate = GetGlobalTaxRate();

            // 更新所有物料的税率
            foreach (DataGridViewRow row in dgvmater.Rows)
            {
                // 更新税率列
                row.Cells["colTaxRate"].Value = globalTaxRate.ToString();

                // 根据原价格和税率计算新价格
                CalculateNewPricesFromOriginal(row.Index);
            }
        }

        /// <summary>
        /// 根据原价格和税率计算新价格
        /// </summary>
        private void CalculateNewPricesFromOriginal(int rowIndex)
        {
            if (rowIndex < 0 || rowIndex >= dgvmater.Rows.Count) return;

            var row = dgvmater.Rows[rowIndex];
            var originalUntaxedCell = row.Cells["colOriginalUntaxedPrice"];
            var originalTaxedCell = row.Cells["colOriginalTaxedPrice"];
            var newUntaxedCell = row.Cells["colUntaxedPrice"];
            var newTaxedCell = row.Cells["colTaxedPrice"];
            var taxRateCell = row.Cells["colTaxRate"];

            // 获取税率
            if (!int.TryParse(taxRateCell.Value?.ToString(), out var taxRate))
            {
                return;
            }

            // 获取原价格
            if (decimal.TryParse(originalUntaxedCell.Value?.ToString(), out var originalUntaxed) &&
                decimal.TryParse(originalTaxedCell.Value?.ToString(), out var originalTaxed))
            {
                // 根据原未税价格和税率计算新价格
                decimal newUntaxedPrice = originalUntaxed;
                decimal newTaxedPrice;

                if (taxRate > 0)
                {
                    newTaxedPrice = originalUntaxed * (1 + taxRate / 100.0m);
                }
                else
                {
                    newTaxedPrice = originalUntaxed;
                }

                // 更新新价格列
                newUntaxedCell.Value = newUntaxedPrice.ToString("F2");
                newTaxedCell.Value = newTaxedPrice.ToString("F2");
            }
        }

        /// <summary>
        /// 获取全局税率
        /// </summary>
        private int GetGlobalTaxRate()
        {
            // 根据实际控件类型获取全局税率
            if (texttax_Rate != null && !string.IsNullOrWhiteSpace(texttax_Rate.Text))
            {
                if (int.TryParse(texttax_Rate.Text, out var taxRate))
                {
                    return taxRate; // 直接返回Int类型，表示百分比
                }
            }

            // 如果没有输入税率，返回0
            return 0;
        }

        /// <summary>
        /// 表格单元格点击事件
        /// </summary>
        private void Dgvmater_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;

            var grid = sender as DataGridView;
            if (grid == null) return;

            var columnName = grid.Columns[e.ColumnIndex].Name;

            if (columnName == "colDelete")
            {
                // 删除当前行
                if (MessageBox.Show("确定要删除这条记录吗？", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    grid.Rows.RemoveAt(e.RowIndex);
                }
            }
        }

        /// <summary>
        /// 数据绑定完成事件
        /// </summary>
        private void Dgvmater_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            var grid = dgvmater;
            if (grid != null)
            {
                // 把删除列放到最后
                if (grid.Columns.Contains("colDelete"))
                {
                    grid.Columns["colDelete"].DisplayIndex = grid.Columns.Count - 1;
                }
            }
        }

        /// <summary>
        /// 单元格值更改事件 - 用于价格计算
        /// </summary>
        private void Dgvmater_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0 || e.ColumnIndex < 0) return;

            var grid = sender as DataGridView;
            if (grid == null) return;

            var columnName = grid.Columns[e.ColumnIndex].Name;

            if (columnName == "colTaxRate")
            {
                // 当税率改变时，重新计算新价格
                RecalculateNewPrices(e.RowIndex);
            }
            else if (columnName == "colUntaxedPrice")
            {
                // 当新未税价格改变时，自动计算新含税价格
                if (decimal.TryParse(grid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value?.ToString(), out var untaxedPrice))
                {
                    var taxRate = GetTaxRate(e.RowIndex);
                    if (taxRate > 0)
                    {
                        var taxedPrice = untaxedPrice * (1 + taxRate / 100.0m);
                        grid.Rows[e.RowIndex].Cells["colTaxedPrice"].Value = taxedPrice.ToString("F2");
                    }
                    else
                    {
                        // 如果税率为0，含税价格等于未税价格
                        grid.Rows[e.RowIndex].Cells["colTaxedPrice"].Value = untaxedPrice.ToString("F2");
                    }
                }
            }
            else if (columnName == "colTaxedPrice")
            {
                // 当新含税价格改变时，自动计算新未税价格
                if (decimal.TryParse(grid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value?.ToString(), out var taxedPrice))
                {
                    var taxRate = GetTaxRate(e.RowIndex);
                    if (taxRate > 0)
                    {
                        var untaxedPrice = taxedPrice / (1 + taxRate / 100.0m);
                        grid.Rows[e.RowIndex].Cells["colUntaxedPrice"].Value = untaxedPrice.ToString("F2");
                    }
                    else
                    {
                        // 如果税率为0，未税价格等于含税价格
                        grid.Rows[e.RowIndex].Cells["colUntaxedPrice"].Value = taxedPrice.ToString("F2");
                    }
                }
            }
        }

        /// <summary>
        /// 获取指定行的税率
        /// </summary>
        private int GetTaxRate(int rowIndex)
        {
            if (rowIndex < 0 || rowIndex >= dgvmater.Rows.Count) return 0;

            var taxRateCell = dgvmater.Rows[rowIndex].Cells["colTaxRate"];
            if (taxRateCell?.Value != null && int.TryParse(taxRateCell.Value.ToString(), out var taxRate))
            {
                return taxRate; // 直接返回Int类型，表示百分比
            }
            return 0;
        }

        /// <summary>
        /// 重新计算指定行的新价格（不改变原价格）
        /// </summary>
        private void RecalculateNewPrices(int rowIndex)
        {
            if (rowIndex < 0 || rowIndex >= dgvmater.Rows.Count) return;

            var row = dgvmater.Rows[rowIndex];
            var untaxedPriceCell = row.Cells["colUntaxedPrice"];
            var taxedPriceCell = row.Cells["colTaxedPrice"];

            if (untaxedPriceCell?.Value != null && decimal.TryParse(untaxedPriceCell.Value.ToString(), out var untaxedPrice))
            {
                var taxRate = GetTaxRate(rowIndex);
                if (taxRate > 0)
                {
                    var taxedPrice = untaxedPrice * (1 + taxRate / 100.0m);
                    taxedPriceCell.Value = taxedPrice.ToString("F2");
                }
                else
                {
                    // 如果税率为0，含税价格等于未税价格
                    taxedPriceCell.Value = untaxedPrice.ToString("F2");
                }
            }
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStepwiseAdd_Click(object sender, EventArgs e)
        {
            // 读取供应商Id
            int? supplierId = null;
            if (cbosupplierId.SelectedValue != null && int.TryParse(cbosupplierId.SelectedValue.ToString(), out var sv))
            {
                supplierId = sv;
            }
            else if (cbosupplierId.SelectedItem is Supplier_TableDtos supplierObj)
            {
                supplierId = supplierObj.Id;
            }
            if (!supplierId.HasValue)
            {
                MessageBox.Show("请先选择供应商", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            // 打开按供应商过滤的物料选择窗体
            var dialog = new SupplierMaterial_Table(supplierId.Value, selected =>
            {
                if (selected == null) return;

                // 检查是否已经添加过该物料
                foreach (DataGridViewRow rows in dgvmater.Rows)
                {
                    if (rows.Cells["colMaterialNumber"].Value?.ToString() == selected.MaterialNumber)
                    {
                        MessageBox.Show("该物料已存在于列表中", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                }

                // 回填到列表
                int rowIndex = dgvmater.Rows.Add();
                var row = dgvmater.Rows[rowIndex];

                // 设置物料信息
                row.Cells["colMaterialNumber"].Value = selected.MaterialNumber;
                row.Cells["colMaterialName"].Value = selected.MaterialName;
                row.Cells["colSpecifications"].Value = selected.Specifications;
                row.Cells["colUnitName"].Value = selected.UnitName;
                row.Cells["colOriginalUntaxedPrice"].Value = selected.OidUntaxedPrice;
                row.Cells["colOriginalTaxedPrice"].Value = selected.OidIncludingTax;

                // 设置全局税率（从页面顶部税率输入框获取）
                int globalTaxRate = GetGlobalTaxRate();
                row.Cells["colTaxRate"].Value = globalTaxRate.ToString();

                // 根据原价格和税率计算新价格
                CalculateNewPricesFromOriginal(rowIndex);

                // 设置行标签，存储物料ID等信息
                row.Tag = selected;
            });
            dialog.ShowDialog(this);
        }


        /// <summary>
        /// 提交
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void skinButton1_Click(object sender, EventArgs e)
        {
            // 验证数据
            if (!ValidateSubmitData())
            {
                return;
            }

            // 提交数据
            SubmitProcurementPricing();
        }

        /// <summary>
        /// 验证提交数据
        /// </summary>
        private bool ValidateSubmitData()
        {
            // 验证是否有物料
            if (dgvmater.Rows.Count == 0)
            {
                MessageBox.Show("请先添加物料", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }

            // 验证供应商是否选择
            if (cbosupplierId.SelectedValue == null)
            {
                MessageBox.Show("请选择供应商", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }

            // 验证税率是否填写
            if (string.IsNullOrWhiteSpace(texttax_Rate.Text))
            {
                MessageBox.Show("请填写税率", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }

            if (!int.TryParse(texttax_Rate.Text, out var taxRate) || taxRate < 0)
            {
                MessageBox.Show("请填写有效的税率", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }

            // 验证所有物料的价格信息
            foreach (DataGridViewRow row in dgvmater.Rows)
            {
                if (string.IsNullOrWhiteSpace(row.Cells["colUntaxedPrice"].Value?.ToString()) ||
                    string.IsNullOrWhiteSpace(row.Cells["colTaxedPrice"].Value?.ToString()))
                {
                    MessageBox.Show("请填写所有物料的价格信息", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return false;
                }

                // 验证价格格式
                if (!decimal.TryParse(row.Cells["colUntaxedPrice"].Value?.ToString(), out var untaxedPrice) ||
                    !decimal.TryParse(row.Cells["colTaxedPrice"].Value?.ToString(), out var taxedPrice))
                {
                    MessageBox.Show("请填写有效的价格", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return false;
                }

                if (untaxedPrice < 0 || taxedPrice < 0)
                {
                    MessageBox.Show("价格不能为负数", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        /// 提交采购核价数据
        /// </summary>
        private async void SubmitProcurementPricing()
        {
            try
            {
                // 显示加载提示
                skinButton1.Enabled = false;
                skinButton1.Text = "提交中...";


                // 构建提交数据
                var items = new List<CreateProcurement_PricingDtos>();

                if (!DateTime.TryParse(datepricing_Date?.text, out var pricingDate))
                {
                    return;
                }


                foreach (DataGridViewRow row in dgvmater.Rows)
                {
                    if (row.Tag is Material_TableDtos material)
                    {
                        var item = new CreateProcurement_PricingDtos
                        {
                            PricingNode = textpricingNode.Text, // 使用已生成的核价编号
                            PricingName = textpricingName.Text, // 获取核价名称
                            Pricing_Date = pricingDate,
                            SupplierId = int.Parse(cbosupplierId.SelectedValue.ToString()), // 供应商ID
                            Tax_Rate = int.Parse(texttax_Rate.Text), // 税率
                            Notes = textnotes.Text, // 获取备注
                            Material_Id = material.Id, // 物料ID
                            Untaxed_Price = decimal.Parse(row.Cells["colUntaxedPrice"].Value.ToString()), // 新未税价格
                            Taxed_Price = decimal.Parse(row.Cells["colTaxedPrice"].Value.ToString()), // 新含税价格
                            State = "待审核" // 默认状态
                        };

                        items.Add(item);
                    }
                }

                if (items.Count == 0)
                {
                    MessageBox.Show("没有有效的物料数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                // 构建请求数据
                var requestData = new { items };

                // 调用API
                var response = await _apiClient.PostAsync<object, TestApiResult<string>>(
                    "api/Write/CreateProcurement_Pricing",
                    requestData);

                if (response != null && response.code == 200)
                {
                    MessageBox.Show("采购核价信息提交成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    // 提交成功后关闭当前窗体，返回到采购核价页面
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
                else
                {
                    MessageBox.Show($"提交失败：{response?.msg ?? "未知错误"}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"提交过程中发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 恢复按钮状态
                skinButton1.Enabled = true;
                skinButton1.Text = "提交";
            }
        }

       

        /// <summary>
        /// 供应商下拉框
        /// </summary>
        /// <returns></returns>
        private async Task LoadSuppliersAsync()
        {
            try
            {
                var resp = await _apiClient.GetAsync<TestCode.TestApiResult<List<Supplier_TableDtos>>>(
                    endpoint: "api/Read/GetSupplier_Table");
                if (resp != null && resp.code == 200)
                {
                    cbosupplierId.DisplayMember = "supplierName";
                    cbosupplierId.ValueMember = "id";
                    cbosupplierId.DataSource = resp.data;
                    cbosupplierId.SelectedItem = null;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载供应商数据失败：{ex.Message}");
            }
        }
    }
}
